#region Using

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;

using Gizmox.WebGUI.Common;
using Gizmox.WebGUI.Forms;
using System.Collections;
using Gizmox.WebGUI.Common.Resources;
using TVC.Layout;
using System.Xml;
using System.IO;
using System.Text.RegularExpressions;
using TVC.Report;
using FlexCel.Core;
using QueryBuilder;
using Gizmox.WebGUI.Common.Interfaces;
using Gizmox.WebGUI.Common.Gateways;

#endregion

namespace TVC.Modules.Act
{
    public partial class NIR : ModuleParent, IHostedApplication
    {
        
        int idAddNew = 248;
        int idEdit = 249;
        int idDelete = 250;
        int idPrint = 251;
        int idToExcel = 257;

        SQLBuilder _sql = new SQLBuilder(processingMode.Details);
        DataTable _dtItemCode = null;
        DataTable _dtSubCode1 = null;
        DataTable _dtSubCode2 = null;
        DataTable _dtDepartment = null;
        DataTable _dtUnit = null;
        public NIR()
        {
            InitializeComponent();
            _strType = "NIR";
            _dgvList = dgvList;
            _dgvFilter = gridFilter1;
            //_strTableName = "TVC_MFMOV";
            _isCheck = true;
            _dgvFilter.GridFiterEvent += new CustomControl.GridFilter.GridFilterHandle(_dgvFilter_GridFiterEvent);
            No.Name = "No";
            ItemCate.Name = "ItemCate";
            SubCode1.Name = "SubCode1";
            SubCode2.Name = "SubCode2";
            Description.Name = "Description";
            ModelPN.Name = "ModelPN";
            Unit.Name = "Unit";
            MinLevel.Name = "MinLevel";
            MaxLevel.Name = "MaxLevel";
            colRemark.Name = "Remark";

        }

        void _dgvFilter_GridFiterEvent(string strFilter, int year)
        {
            string sErr = "";
            BUS.ItemRequestControl MMQCtr = new BUS.ItemRequestControl();
            DataTable dtb = null;
            dtb = MMQCtr.GetbyFilter(GetMainForm().SUNDB, strFilter, ref sErr);
            if (!string.IsNullOrEmpty(gridFilter1.SortField))
            {
                dtb.DefaultView.Sort = gridFilter1.SortField + " " + gridFilter1.Direction;
            }
            bisNIR.DataSource = dtb;
            //dgvList.Columns["colSelect"].Visible = false;
            //dgvList.RowHeadersWidth = 20;
            //dgvList.RowHeadersVisible = true;

        }
        #region .::| Override Functions |::.
        protected override ErrorStatus validateForm(ref string sErr)
        {
            ErrorStatus result = ErrorStatus.SUCCESS;
            sErr = "";
            if (txRequestNo.Text.Trim() == "")
            {
                sErr = "Could not save blank Request, please check!";
                errProvider.SetError(txRequestNo, sErr);
                sErr += "\n";
                txRequestNo.Focus();
                result = ErrorStatus.ERROR;
            }
            else errProvider.SetError(txRequestNo, "");
            if (dpRequestDate.Text == "" || dpRequestDate.Value == null)
            {
                sErr = "Could not save blank Request Date, please check!";
                errProvider.SetError(dpRequestDate, sErr);
                sErr += "\n";
                dpRequestDate.Focus();
                result = ErrorStatus.ERROR;
            }
            else errProvider.SetError(dpRequestDate, "");
            return result;
        }

        protected override bool checkExists()
        {
            BUS.ItemRequestControl ctr = new BUS.ItemRequestControl();
            return ctr.IsExist(GetMainForm().SUNDB, txRequestNo.Text);

        }

        protected override string addRecord(bool isDraft = false)
        {
            string sErr = "";
            BUS.ItemRequestControl ctr = new BUS.ItemRequestControl();
            BUS.ItemRequestDetailControl ctrDet = new BUS.ItemRequestDetailControl();
            object trans = ctr.BeginTransaction(ref sErr);
            ctrDet.SetTransaction(trans);
            DTO.ItemRequestInfo info = GetData();
            info.DTB = GetMainForm().SUNDB;
            if (sErr == "") sErr = SaveMaterialDetail(info.DTB, ctrDet);

            if (sErr == "") ctr.Add(info, ref sErr);

            if (sErr == "") ctr.CommitTransaction(ref sErr);
            else ctr.RollbackTransaction(ref sErr);

            return sErr;
        }


        protected override string updateRecord(bool isDraft = false)
        {
            string sErr = "";
            BUS.ItemRequestControl ctr = new BUS.ItemRequestControl();
            BUS.ItemRequestDetailControl ctrDet = new BUS.ItemRequestDetailControl();
            object trans = ctr.BeginTransaction(ref sErr);
            ctrDet.SetTransaction(trans);
            DTO.ItemRequestInfo info = GetData();
            info.DTB = GetMainForm().SUNDB;
            if (sErr == "") sErr = SaveMaterialDetail(info.DTB, ctrDet);

            if (sErr == "") sErr = ctr.Update(info);

            if (sErr == "") ctr.CommitTransaction(ref sErr);
            else ctr.RollbackTransaction(ref sErr);
            return sErr;
        }
        protected override string delRecord()
        {
            string sErr = "";
            BUS.ItemRequestControl ctr = new BUS.ItemRequestControl();
            BUS.ItemRequestDetailControl ctrDet = new BUS.ItemRequestDetailControl();
            object trans = ctr.BeginTransaction(ref sErr);
            ctrDet.SetTransaction(trans);

            if (sErr == "") sErr = ctr.Delete(GetMainForm().SUNDB, txRequestNo.Text);
            if (sErr == "") sErr = ctrDet.Delete(GetMainForm().SUNDB, txRequestNo.Text);

            if (sErr == "") ctr.CommitTransaction(ref sErr);
            else ctr.RollbackTransaction(ref sErr);
            return sErr;
        }



        protected override void refreshForm(string str)
        {
            txRequestNo.Text = str;
            dpRequestDate.Text = str;
            txApproveBy.Text = GetMainForm().PODInfo.USER_NAME;
            txRequestedBy.Text = GetMainForm().PODInfo.USER_NAME;
            lvDetail.Items.Clear();
        }
        protected override void enableForm(bool val)
        {
            txRequestNo.Enabled = val;
            txRequestedBy.Enabled = val;
            dpRequestDate.Enabled = val;
            txApproveBy.Enabled = val;
            errProvider.SetError(txRequestNo, "");
            toolStrip1.Enabled = val;
            btAddRow.Enabled = val;
            btDeleteRow.Enabled = val;
            _EnabledlvDetail = val;
            //lvDetail.Columns[2].
            //lvDetail.e = val;
            EnabledlvDetail();
        }

        private void EnabledlvDetail()
        {
            LoadDetail(txRequestNo.Text);
        }

        protected override void loadRecord(object o)
        {
            if (o is DataRowView)
            {
                DTO.ItemRequestInfo inf = new DTO.ItemRequestInfo((DataRowView)o);
                SetData(inf);
            }
        }

        private void SetData(DTO.ItemRequestInfo inf)
        {
            txRequestNo.Text = inf.RequestRef;
            dpRequestDate.Value = Convert.ToDateTime(inf.RequestDate);

            txRequestedBy.Text = inf.PreparedBy;
            txApproveBy.Text = inf.ApprovedBy;
            LoadDetail(inf.RequestRef);
        }

        #endregion
        private DTO.ItemRequestInfo GetData()
        {
            DTO.ItemRequestInfo inf = new DTO.ItemRequestInfo()
            {
                DTB = GetMainForm().SUNDB,
                RequestRef = txRequestNo.Text,
                RequestDate = dpRequestDate.Value,
                PreparedBy = txRequestedBy.Text,
                ApprovedBy = txApproveBy.Text,
                CreatedBy = GetMainForm().PODInfo.USER_ID,
                CreatedDate = DateTime.Now,
                ModifiedBy = GetMainForm().PODInfo.USER_ID,
                ModifiedDate = DateTime.Now
            };
            return inf;
        }

        private string SaveMaterialDetail(string db, BUS.ItemRequestDetailControl ctrDet)
        {
            string sErr = "";
            string reqNo = txRequestNo.Text;
            DTO.ItemRequestDetailInfo info = new DTO.ItemRequestDetailInfo();
            DataTable dt = DTO.ItemRequestDetailInfo.ToDataTable();
            ctrDet.Delete(db, reqNo);

            foreach (ListViewItem it in lvDetail.Items)
            {
                if (sErr != "") return sErr;
                DataRow row = info.ToDataRow(dt);
                row["DetailNo"] = it.Index + 1; //it.SubItems[No.Index].Text;
                row["ItemDescription"] = ((CustomControl.ColTextGird)((ListViewItem.ListViewSubControlItem)it.SubItems[Description.Index]).Control).Value + "";
                row["Unit"] = it.SubItems[Unit.Index].Text;
                row["ItemCate"] = ((CustomControl.LookupBox)((ListViewItem.ListViewSubControlItem)it.SubItems[ItemCate.Index]).Control).Value;
                row["SubCode1"] = ((CustomControl.LookupBox)((ListViewItem.ListViewSubControlItem)it.SubItems[SubCode1.Index]).Control).Value;
                row["SubCode2"] = ((CustomControl.LookupBox)((ListViewItem.ListViewSubControlItem)it.SubItems[SubCode2.Index]).Control).Value;
                row["PartNo"] = ((CustomControl.ColTextGird)((ListViewItem.ListViewSubControlItem)it.SubItems[ModelPN.Index]).Control).Value;
                row["Department"] = ((ComboBox)((ListViewItem.ListViewSubControlItem)it.SubItems[Department.Index]).Control).SelectedValue;
                row["Remark"] = ((TextBox)((ListViewItem.ListViewSubControlItem)it.SubItems[colRemark.Index]).Control).Text;
                row["MinLevel"] = ((NumericUpDown)((ListViewItem.ListViewSubControlItem)it.SubItems[MinLevel.Index]).Control).Value;
                row["MaxLevel"] = ((NumericUpDown)((ListViewItem.ListViewSubControlItem)it.SubItems[MaxLevel.Index]).Control).Value;
                if (sErr != "") return sErr;

                info = new DTO.ItemRequestDetailInfo(row);
                if (info.ItemCate == "") continue;
                info.DTB = db;
                info.RequestRef = reqNo;
                ctrDet.Add(info, ref sErr);
            }

            return sErr;
        }

        private object GetValue(ListViewItem.ListViewSubItem listViewSubItem)
        {
            ListViewItem.ListViewSubControlItem tmp = listViewSubItem as ListViewItem.ListViewSubControlItem;
            if (tmp == null) return listViewSubItem.Text;

            if (tmp.Control is TextBox)
                return tmp.Control.Text;

            if (tmp.Control is ComboBox)
                return ((ComboBox)tmp.Control).SelectedValue;

            if (tmp.Control is NumericUpDown)
                return ((NumericUpDown)tmp.Control).Value;

            if (tmp.Control is CustomControl.DateTimeCustom)
                return ((CustomControl.DateTimeCustom)tmp.Control).Value;

            if (tmp.Control is CustomControl.LookupBox)
                return ((CustomControl.LookupBox)tmp.Control).Value;

            return DBNull.Value;
        }
        public void LoadDetail(string RequestNo)
        {
            string sErr = "";

            BUS.ItemRequestDetailControl cdCrt = new BUS.ItemRequestDetailControl();
            DataTable dt = cdCrt.GetAll(GetMainForm().SUNDB, RequestNo, ref sErr);

            BindListView(dt);

        }
        private void BindListView(DataTable dt)
        {
            this.lvDetail.SuspendLayout();
            this.lvDetail.Items.Clear();
            foreach (DataRow r in dt.Rows)
            {
                AddNewDetail(r, _EnabledlvDetail);
            }
            this.lvDetail.ResumeLayout(true);
        }

        //DTO.ItemRequestDetailInfo inf = new DTO.ItemRequestDetailInfo();
        //    if (Regex.IsMatch(txRows.Text, "[0-9]+"))
        //    {
        //        DataTable dt = DTO.ItemRequestDetailInfo.ToDataTable();
        //        for (int i = 0; i < Convert.ToInt32(txRows.Text); i++)
        //        {
        //            AddNewDetail(inf.ToDataRow(dt), _EnabledlvDetail);
        //        }
        //    }
        private void AddNewDetail(DataRow r, bool Val)
        {
            ListViewItem objItem = new ListViewItem();
            lvDetail.Items.Add(objItem);
            objItem.SubItems.Add(string.Format("{0}", objItem.Index + 1));
            CustomControl.LookupBox lk = new CustomControl.LookupBox()
            {
                //  TabIndex = lvDetail.Items.Count * lvDetail.Columns.Count + i,
                DisplayMember = "ItemCate",
                ValueMember = "ItemCate",
                Name = "ItemCate",
                MainForm = GetMainForm(),
                Lookup = "ItemCate",
                Enabled = Val,
                //AutoCompleteMode = lkBudgetCode.AutoCompleteMode,
                DataSource = _dtItemCode.Copy(),
                // DropDownStyle = lkBudgetCode.DropDownStyle,
                Value = string.Format("{0}", r["ItemCate"]),
                Top = 1,
                Tag = objItem

            };

            objItem.SubItems.Add(lk);
            lk.SelectedValueChanged += new EventHandler(ItemCode_SelectedValueChanged);

            CustomControl.LookupBox Sub1 = new CustomControl.LookupBox()
            {
                DisplayMember = "typevalue",
                ValueMember = "typevalue",
                Name = "SubCode1",
                MainForm = GetMainForm(),
                Lookup = "SubCode1",
                Enabled = Val,
                DataSource = _dtSubCode1.Copy(),
                Value = string.Format("{0}", r["SubCode1"]),
                Top = 1,
                Tag = objItem

            };
            objItem.SubItems.Add(Sub1);

            CustomControl.LookupBox Sub2 = new CustomControl.LookupBox()
            {
                DisplayMember = "typevalue",
                ValueMember = "typevalue",
                Name = "SubCode2",
                MainForm = GetMainForm(),
                Lookup = "SubCode2",
                Enabled = Val,
                DataSource = _dtSubCode2.Copy(),
                Value = string.Format("{0}", r["SubCode2"]),
                Top = 1,
                Tag = objItem
            };
            objItem.SubItems.Add(Sub2);

            CustomControl.ColTextGird ColText = new CustomControl.ColTextGird(Val, 540, string.Format("{0}", r["ItemDescription"]));
            {
                ColText.AutoValidate = Gizmox.WebGUI.Forms.AutoValidate.EnablePreventFocusChange;
                ColText.Value = string.Format("{0}", r["ItemDescription"]);
                ColText.Name = "Description";
                ColText.FrmName = "Item Description";
                ColText.FrmEnabled = Val;
                ColText.Enabled = true;
                Tag = objItem;
            }
            //objItem.SubItems.Add(string.Format("{0}", r["Description"]));
            objItem.SubItems.Add(ColText);
            CustomControl.ColTextGird ColPN = new CustomControl.ColTextGird(Val, 90, string.Format("{0}", r["PartNo"]));
            {
                ColPN.AutoValidate = Gizmox.WebGUI.Forms.AutoValidate.EnablePreventFocusChange;
                ColPN.Value = string.Format("{0}", r["PartNo"]);
                ColPN.Name = "PartNo";
                ColPN.FrmEnabled = Val;
                ColPN.Enabled = true;
                ColPN.FrmName = "PartNo";
                //ColText.Enabled = Val;
                Tag = objItem;
            }
            objItem.SubItems.Add(ColPN);
            ComboBox Unit = new ComboBox()
            {
                //  TabIndex = lvDetail.Items.Count * lvDetail.Columns.Count + i,
                DisplayMember = "Code",
                ValueMember = "Code",
                Name = "Unit",
                Enabled = Val,
                DataSource = _dtUnit.Copy(),
                AutoCompleteMode = Gizmox.WebGUI.Forms.AutoCompleteMode.SuggestAppend,
                // DropDownStyle = lkBudgetCode.DropDownStyle,
                SelectedValue = string.Format("{0}", r["Unit"]) + "",
                Top = 1,
                Tag = objItem
            };
            objItem.SubItems.Add(Unit);
            ComboBox Dept = new ComboBox()
            {
                //  TabIndex = lvDetail.Items.Count * lvDetail.Columns.Count + i,
                DisplayMember = "Code",
                ValueMember = "Code",
                Name = "Department",
                Enabled = Val,
                AutoCompleteMode = Gizmox.WebGUI.Forms.AutoCompleteMode.SuggestAppend,
                DataSource = _dtDepartment.Copy(),
                // DropDownStyle = lkBudgetCode.DropDownStyle,
                SelectedValue = string.Format("{0}", r["Department"]) + "",
                Top = 1,
                Tag = objItem
            };
            objItem.SubItems.Add(Dept);
            //objItem.SubItems.Add(string.Format("{0}", r["Unit"]));
            objItem.SubItems.Add(new NumericUpDown()
            {
                //  TabIndex = lvDetail.Items.Count * lvDetail.Columns.Count + i,
                Minimum = -999999999999,
                Maximum = 999999999999,
                DecimalPlaces = 0,
                Value = r["MinLevel"] == DBNull.Value ? 0 : Convert.ToDecimal(r["MinLevel"]),
                ThousandsSeparator = true,
                HideButtons = true,
                Enabled = Val,
                Name = "MinLevel",

                Tag = objItem,
                TextAlign = HorizontalAlignment.Right


            });
            objItem.SubItems.Add(new NumericUpDown()
            {
                //  TabIndex = lvDetail.Items.Count * lvDetail.Columns.Count + i,
                Minimum = -999999999999,
                Maximum = 999999999999,
                DecimalPlaces = 0,
                Value = r["MaxLevel"] == DBNull.Value ? 0 : Convert.ToDecimal(r["MaxLevel"]),
                ThousandsSeparator = true,
                HideButtons = true,
                Enabled = Val,
                Name = "MaxLevel",

                Tag = objItem,
                TextAlign = HorizontalAlignment.Right


            });
            //dataGridViewCellStyle6.Alignment = Gizmox.WebGUI.Forms.DataGridViewContentAlignment.MiddleRight;
            //objItem.SubItems.Add(new TextBox()
            //{
            //    // TabIndex = lvDetail.Items.Count * lvDetail.Columns.Count + i,
            //    Text = string.Format("{0}", r["GLAccount"]),
            //    Name = "GLAccount",
            //    Tag = objItem
            //});
            //objItem.SubItems.Add(new TextBox()
            //{
            //    // TabIndex = lvDetail.Items.Count * lvDetail.Columns.Count + i,
            //    Text = string.Format("{0}", r["BudgetCode"]),
            //    Name = "BudgetCode",
            //    Tag = objItem
            //});
            TextBox tx = new TextBox()
            {
                // TabIndex = lvDetail.Items.Count * lvDetail.Columns.Count + i,
                Text = string.Format("{0}", r["Remark"]),
                Name = "Remark",
                Enabled = Val,
                Tag = objItem,
                MaxLength = 255,
            };


            tx.LostFocus += (sender, e) =>
            {
                NextItem(tx.Tag);
            };
            objItem.SubItems.Add(tx);
            lk.Focus();
        }
        bool _isCal = true;
        private bool _EnabledlvDetail = false;
        void ItemCode_SelectedValueChanged(object sender, EventArgs e)
        {
            if (_isCal)
            {
                // lvDetail.SuspendLayout();
                _isCal = false;
                if (sender is CustomControl.LookupBox)
                {
                    CustomControl.LookupBox lk = sender as CustomControl.LookupBox;
                    ListViewItem it = lk.Tag as ListViewItem;
                    DataRowView rv = lk.SelectedItem as DataRowView;

                    if (rv != null)
                    {
                        BUS.TVC_CATE1Control sub = new BUS.TVC_CATE1Control();
                        String maingroup = string.Format("{0}", rv["maingroup"]);
                        _dtSubCode1 = sub.GetSubCode1(maingroup, ref sErr);
                        _dtSubCode2 = sub.GetSubCode2(maingroup, ref sErr);
                        ((CustomControl.LookupBox)((ListViewItem.ListViewSubControlItem)it.SubItems[SubCode1.Index]).Control).DataSource = _dtSubCode1;
                        ((CustomControl.LookupBox)((ListViewItem.ListViewSubControlItem)it.SubItems[SubCode1.Index]).Control).Value = "";
                        ((CustomControl.LookupBox)((ListViewItem.ListViewSubControlItem)it.SubItems[SubCode2.Index]).Control).DataSource = _dtSubCode2;
                        ((CustomControl.LookupBox)((ListViewItem.ListViewSubControlItem)it.SubItems[SubCode2.Index]).Control).Value = "";
                    }
                }
                // lvDetail.ResumeLayout(true);
                _isCal = true;

            }
        }


        private void NextItem(object o)
        {
            ListViewItem it = o as ListViewItem;
            if (it.Index != lvDetail.Items.Count - 1)
            {
                ListViewItem next = lvDetail.Items[it.Index + 1];
                ListViewItem.ListViewSubControlItem nextControl = next.SubItems[1] as ListViewItem.ListViewSubControlItem;
                nextControl.Control.Focus();
            }
        }

        public void InitializeApplication()
        {
        }

        //public void AddNew()
        //{

        //}

        public void SetObject(object obj)
        {
        }

        public HostedToolBarElement[] GetToolBarElements()
        {
            ArrayList objElements = new ArrayList();
            if (IsPermis(idAddNew)) objElements.Add(new HostedToolBarButton("Add New", "New", new IconResourceHandle("Add.png"), "C"));
            if (IsPermis(idAddNew))
                objElements.Add(new HostedToolBarButton("Copy", "Copy", new IconResourceHandle("Copy.png"), "O"));
            if (IsPermis(idEdit)) objElements.Add(new HostedToolBarButton("Edit", "Edit", new IconResourceHandle("Edit.png"), "A"));
            if (IsPermis(idAddNew) && IsPermis(idEdit)) objElements.Add(new HostedToolBarButton("Save", "Save", new IconResourceHandle("Save.png"), "S", false));

            objElements.Add(new HostedToolBarButton("Skip", "Skip", new IconResourceHandle("Reject.png"), "K", false));
            if (IsPermis(idDelete)) objElements.Add(new HostedToolBarButton("Delete", "Delete", new IconResourceHandle("Delete.png"), "X"));

            // if (IsPermis(idPrint)) objElements.Add(new HostedToolBarButton("Print", "To excel", new IconResourceHandle("Print.png"), "P"));
            if (IsPermis(idToExcel)) objElements.Add(new HostedToolBarButton("To Excel", "To Excel", new IconResourceHandle("Print.png"), "E", false));
            //if (IsPermis(idTransferOut)) objElements.Add(new HostedToolBarButton("To Excel", "To Excel", new IconResourceHandle("Excel.png"), "E", false));

            objElements.Add(new HostedToolBarButton("Refresh", new IconResourceHandle("Refresh.png"), "R"));

            return (HostedToolBarElement[])objElements.ToArray(typeof(HostedToolBarElement));
        }

        public void OnToolBarButtonClick(HostedToolBarButton objButton, EventArgs objEvent)
        {
            sErr = "";
            string strAction = (string)objButton.Tag;

            BUS.ContractControl ctr = new BUS.ContractControl();
            switch (strAction)
            {
                case "C":
                    AddNew(txRequestNo);
                    break;
                case "A":
                    editRecord(txRequestNo);
                    break;
                case "S":
                    saveRecord(txRequestNo);
                    break;
                case "O":
                    copy(txRequestNo);
                    break;
                case "P":

                    break;
                case "E":
                    {
                        _sql = SQLBuilder.LoadSQLBuilderFromDataBase("ItemReq01_" + GetMainForm().PODInfo.Business_ID, "TVC", "");
                        if (txRequestNo.Text.Trim() != "")
                        {
                            _sql.Filters[0].ValueFrom = txRequestNo.Text.Trim();
                            _sql.Filters[0].ValueTo = "";
                            _sql.Filters[0].FilterFrom = txRequestNo.Text.Trim();
                        }
                        else
                        {
                            _sql.Filters[0].ValueFrom = "ZZZ";
                            _sql.Filters[0].ValueTo = "";
                            _sql.Filters[0].FilterFrom = "ZZZ";
                        }
                        //_sql.Filters[0].ValueFrom = txRequestNo.Text;
                        //_sql.Filters[0].FilterFrom = "ZZZ";
                        //_sql.Filters[0].ValueTo = "";

                        ReportGenerator.User2007 = false;
                        ReportGenerator _report = new ReportGenerator(_sql, "ItemReq01_" + GetMainForm().PODInfo.Business_ID, "", MainForm.AppConnectString, MainForm.ServerPath + "ReportTemplate\\", MainForm.ServerPath + "Report\\", "");
                        _report.UserID = GetMainForm().PODInfo.USER_ID;
                        ExcelFile exfile = _report.CreateReport();
                        ExcelFile file = exfile;
                        MemoryStream ms = new MemoryStream();
                        file.Save(ms);

                        DownloadGateway myDownload = new DownloadGateway(ms, "ItemReq01_" + GetMainForm().PODInfo.Business_ID + ".xls");

                        myDownload.ContentType = "application/vnd.ms-excel";
                        myDownload.StartDownload(this);
                    }
                    break;
                case "K":
                    skip();
                    break;
                case "X":
                    delete(txRequestNo);
                    break;

                case "R":
                    reloadList();
                    break;

            }
            if (sErr == "") ThrowMsg("Command: " + _processStatus);
        }

        private void NIR_Load(object sender, EventArgs e)
        {
            BUS.TVC_CATE1Control ctr = new BUS.TVC_CATE1Control();
            _dtItemCode = ctr.GetItemCate(ref sErr);
            BUS.TVC_CATE1Control sub = new BUS.TVC_CATE1Control();
            String maingroup = "";
            _dtSubCode1 = sub.GetSubCode1(maingroup, ref sErr);
            _dtSubCode2 = sub.GetSubCode2(maingroup, ref sErr);
            BUS.TVC_LOOKUPControl lk = new BUS.TVC_LOOKUPControl(GetMainForm().PODInfo.Business_ID);
            _dtDepartment = lk.GetDepartment(GetMainForm().SUNDB, ref sErr);
            _dtDepartment.Rows.Add(_dtDepartment.NewRow());
            _dtUnit = lk.GetUnit(GetMainForm().SUNDB, ref sErr);
            _dtUnit.Rows.Add(_dtUnit.NewRow());
            refreshForm("");
            enableForm(false);
        }


        private void btAddRow_Click(object sender, EventArgs e)
        {
            DTO.ItemRequestDetailInfo inf = new DTO.ItemRequestDetailInfo();
            if (Regex.IsMatch(txRows.Text, "[0-9]+"))
            {
                DataTable dt = DTO.ItemRequestDetailInfo.ToDataTable();
                for (int i = 0; i < Convert.ToInt32(txRows.Text); i++)
                {
                    AddNewDetail(inf.ToDataRow(dt), _EnabledlvDetail);
                }
            }
        }

        private void btDeleteRow_Click(object sender, EventArgs e)
        {
            if (lvDetail.SelectedIndex >= 0)
                lvDetail.Items.RemoveAt(lvDetail.SelectedIndex);
        }

        //private void lvDetail_MenuClick(object objSource, MenuItemEventArgs objArgs)
        //{
        //    if (!lvDetail.Enabled)
        //    {
        //        Forms.frmPopupText frm = new Forms.frmPopupText();
        //        frm.Value = textBox1.Text;
        //        frm.EnableBox = false;
        //        frm.Text = "Item Description";
        //        frm.FormClosed += (form, args) =>
        //        {
        //            if (((Forms.frmPopupText)form).DialogResult == DialogResult.OK)
        //            {
        //                textBox1.Text = frm.Value;
        //            }
        //            textBox1.Focus();
        //        };
        //        frm.ShowDialog();
        //    }
        //}

    }
}